
var miniFeed;
var lastFeedLength;
var timerRoutine;
var nbAttempt = 0;
var r = 0;
var aStoryNodes;
var totalDeleted = 0;
var working = false;
var hiddePost;


// ****************************************** OK ******************************************************
function goClean()
{
	if (confirm("Be careful, it will definitely erase your posts.\nDo you want to continue ?")) {
		
		getMiniFeed();
		document.getElementById('cmw_statsContent').style.display = '';
		
	}
}


// ****************************************** OK ******************************************************
function stopCleaning()
{
	document.getElementById('cmw_goButton').disabled = '';
	document.getElementById('cmw_stopButton').disabled = 'disabled';
	document.getElementById('cmw_infosdiv').style.display = 'none';
	document.getElementById('cmw_warningdiv').style.display = '';
	document.getElementById('cmw_statusMsg').innerHTML = 'Cleaning stopped !!';
	window.clearTimeout(timerRoutine);
}

// ****************************************** OK ******************************************************
function endCleaning()
{
	stopCleaning();
	document.getElementById('cmw_statusMsg').innerHTML = 'Cleaning finished !';
}


// ****************************************** OK ******************************************************
function closeCleaning()
{
	stopCleaning();
	var clDiv = document.getElementById('cleanupModalDiv');
	document.body.removeChild(clDiv);
}
 

// ****************************************** OK ******************************************************
function simulateClick(elm) {
	
	if (elm.dispatchEvent) {
		elm.onclick = function() { return true;};
		var evt = document.createEvent("MouseEvents");
		evt.initEvent("click", true, true);
		elm.dispatchEvent(evt);
		if(elm.className.indexOf('uiMorePagerPrimary') > -1) {
			$("html,body").animate({scrollTop:((nbAttempt+1)*document.body.scrollHeight)}, 'fast');
		}
		else{
			$("html,body").animate({scrollTop:((nbAttempt+1)*document.body.scrollHeight)}, 'fast');
		}
	} else {
		elm.click();
		$("html,body").animate({scrollTop:((nbAttempt+1)*document.body.scrollHeight)}, 'fast');
			
	}
}

// ****************************************** OK ******************************************************
function searchOlderPosts()
{
	
	var bottomPageLinks = document.getElementById('pagelet_timeline_recent_more_pager').getElementsByTagName('a');
	if (bottomPageLinks.length > 0) {
		for (var i = 0; i < bottomPageLinks.length; i++) {
			
			if (bottomPageLinks[i].className.indexOf('uiMorePagerPrimary') > -1) {
				
				document.getElementById('cmw_statusMsg').innerHTML = 'Searching for older posts... <img src="http://www.mysoundisdope.com/wait.gif" align="absmiddle" border="0" />';
				simulateClick(bottomPageLinks[i]);
				return true;
			
			}
		}
				$("html,body").animate({scrollTop:((nbAttempt+1)*document.body.scrollHeight)}, 'fast');
				return true;
		
	} else {
			 $("html,body").animate({scrollTop:((nbAttempt+1)*document.body.scrollHeight)}, 'fast');
			return true;

	}
}


// ****************************************** OK ******************************************************
function submitPopDelete()
{
	var aInputs = document.getElementById('pop_content').getElementsByTagName('input');
	for (var i = 0; i < aInputs.length; i++) {
		if (aInputs[i].name == "ok") {
			var submitButton = aInputs[i];
			simulateClick(submitButton);
			totalDeleted++;
			document.getElementById('cmw_nbTotalDeleted').innerHTML = totalDeleted;
			working = false;
		}
	}
}


var waitingPopDelete = true;

// ****************************************** OK ******************************************************
function clickDelete(crossLink)
{
	if (document.getElementById('pop_content')) {
		waitingPopDelete = false;
		submitPopDelete();
	} else {
		simulateClick(crossLink);
	}
	
	if(waitingPopDelete) {
		window.setTimeout(function() {
			clickDelete(crossLink);
        }, 2000);
	}
}

// ****************************************** OK ******************************************************
function clickCover(crossLink)
{
		simulateClick(crossLink);
}

// ****************************************** OK ******************************************************
var waitingDeleteSubMenuDeletable = true;
function isNotDeletable(crossLink)
{
	var isOK;

		var checkSubMenu = crossLink.parentNode.getElementsByTagName('div');
		if (checkSubMenu.length > 0) {
				waitingDeleteSubMenuDeletable = false;
				var ulSubMenu = checkSubMenu[0].getElementsByTagName('div')[0].getElementsByTagName('ul')[0];
				var rmLink = ulSubMenu.getElementsByTagName('a');
						for(var i=0; i < rmLink.length; i++) {
							linkAtt = rmLink[i].getAttribute('ajaxify');
							if (linkAtt) {
								if (linkAtt.indexOf('remove_content') > -1|| linkAtt.indexOf('remove_and_delete_photo') > -1) {
									return false;
								}
							}
						}
						for(var i=0; i < rmLink.length; i++) {
							linkAtt = rmLink[i].getAttribute('ajaxify');
							if (linkAtt) {
								if (linkAtt.indexOf('customize_action=2') > -1 && !(linkAtt.indexOf('customize_action=21') > -1 || linkAtt.indexOf('customize_action=22') > -1 ||
									linkAtt.indexOf('customize_action=23') > -1 || linkAtt.indexOf('customize_action=20') > -1 || linkAtt.indexOf('customize_action=24') > -1||
									linkAtt.indexOf('customize_action=25') > -1 || linkAtt.indexOf('customize_action=26') > -1 || linkAtt.indexOf('customize_action=27') > -1 ||
									linkAtt.indexOf('customize_action=28') > -1|| linkAtt.indexOf('customize_action=29') > -1 || linkAtt.indexOf('customize_action=2&') > -1)) {
										
										return true;
								}
							}
					}
			} 
			
	else {
		simulateClick(crossLink);
		waitingDeleteSubMenuDeletable = true;
	}
		
	if(waitingDeleteSubMenu) {
		window.setTimeout(function() {
			 isOK = isNotDeletable(crossLink)
        }, 2000);
		return isOK;
	}
	else{
		return false;
	}
}

// ****************************************** OK ******************************************************
var waitingDeleteSubMenu = true;
var deleteOK = 0;
function getDeleteSubMenu(crossLink)
{
	deleteOK = 0;

	var checkSubMenu = crossLink.parentNode.getElementsByTagName('div');
	if (checkSubMenu.length > 0) {
		waitingDeleteSubMenu = false;
		
		var ulSubMenu = checkSubMenu[0].getElementsByTagName('div')[0].getElementsByTagName('ul')[0];
		var rmLink = ulSubMenu.getElementsByTagName('a');
		if(rmLink.length > 0) {
			for(var i=0; i < rmLink.length; i++) {
				linkAtt = rmLink[i].getAttribute('ajaxify');
				if (linkAtt) {
					if (linkAtt.indexOf('remove_content') > -1 ){
						clickDelete(rmLink[i]);
						i = rmLink.length;
						deleteOK = 1;
					}
				}
			}
			if(deleteOK == 0){
				for(var i=0; i < rmLink.length; i++) {
					
					linkAtt = rmLink[i].getAttribute('ajaxify');
					if (linkAtt) {
						if (linkAtt.indexOf('customize_action=2') > -1 && !(linkAtt.indexOf('customize_action=21') > -1 || linkAtt.indexOf('customize_action=22') > -1 ||
							linkAtt.indexOf('customize_action=23') > -1 || linkAtt.indexOf('customize_action=20') > -1 || linkAtt.indexOf('customize_action=24') > -1||
							linkAtt.indexOf('customize_action=25') > -1 || linkAtt.indexOf('customize_action=26') > -1 || linkAtt.indexOf('customize_action=27') > -1 ||
							linkAtt.indexOf('customize_action=28') > -1|| linkAtt.indexOf('customize_action=29') > -1 || linkAtt.indexOf('customize_action=2&') > -1)) {
						
							if(hiddePost.options[hiddePost.selectedIndex].value == 1){
								clickCover(rmLink[i]);
							}
							i = rmLink.length;
							totalDeleted++;
							document.getElementById('cmw_nbTotalDeleted').innerHTML = totalDeleted;
							working = false;
						}
					}
				}		
			}
		}
	} else {
		simulateClick(crossLink);
		working = false;
	}
		
	if(waitingDeleteSubMenu) {
		window.setTimeout(function() {
			 getDeleteSubMenu(crossLink)
        }, 2000);
	}
}

// ****************************************** OK ******************************************************
function deletePost(storyNode)
{
	
	var zNodes = storyNode.getElementsByTagName('a');
	
    for (var i = 0; i < zNodes.length; i++) {
		if ((zNodes[i].className.indexOf('uiCloseButton') > -1) || (zNodes[i].className.indexOf('uiSelectorButton') > -1)) {
			var crossLink = zNodes[i];
		
			if (crossLink.className.indexOf('uiSelectorButton') < 0) {
				clickDelete(crossLink);
			}
			else {
	            getDeleteSubMenu(crossLink);
            }
			i = zNodes.length;
		}
	}
}

// ****************************************** OK ******************************************************
function isPostDeletable(storyNode)
{
	
	var zNodes = storyNode.getElementsByTagName('a');

    for (var i = 0; i < zNodes.length; i++) {
		if ((zNodes[i].className.indexOf('uiCloseButton') > -1) || (zNodes[i].className.indexOf('uiSelectorButton') > -1)) {
			var crossLink = zNodes[i];
            return  isNotDeletable(crossLink);
			i = zNodes.length;
		}
	}
	return false;
}

// ****************************************** OK ******************************************************
function cleanRoutine()
{
	if (working == false) {
		
		if (document.getElementById('pop_content')) {
			
			submitPopDelete();
			
			window.clearTimeout(timerRoutine);
			timerRoutine = window.setTimeout(function(){
				cleanRoutine();
			}, 2000);
		}
		
		else {
			working = true;
			waitingDeleteSubMenu = true;
			waitingPopDelete = true;
			
			if (r < aStoryNodes.length) {
				var storyNode = aStoryNodes[r];
				deletePost(storyNode);
				document.getElementById('cmw_nbCurrentlyCleaning').innerHTML = (r + 1);
				window.clearTimeout(timerRoutine);
				timerRoutine = window.setTimeout(function(){
					cleanRoutine();
				}, 5000);
				r++;
				$("html,body").animate({scrollTop:0}, 'fast');
			}
			else {
				
				searchOlderPosts();
				window.clearTimeout(timerRoutine);
				timerRoutine = window.setTimeout(function(){
					getMiniFeed();
				}, 8000);
				
				working = false;
			}
		}
	} else {
		window.clearTimeout(timerRoutine);
		timerRoutine = window.setTimeout(function(){
			cleanRoutine();
		}, 1000);
	}
    return true;
}

var feedNodes;
// ****************************************** OK ******************************************************
function getMiniFeed()
{
	 
	document.getElementById('cmw_stopButton').disabled = '';
	document.getElementById('cmw_goButton').disabled = 'disabled';
	document.getElementById('cmw_infosdiv').style.display = '';
	document.getElementById('cmw_statusMsg').innerHTML = 'Cleaning, please wait...';
	document.getElementById('cmw_warningdiv').style.display = 'none';
	
    r = 0;
    aStoryNodes = new Array();
	
	miniFeedTwo = document.getElementsByClassName("clearfix fbTimelineCapsule");
	
	hiddePost = document.getElementById('cmw_slcfromhdde');
	document.getElementById('cmw_nbWallPosts').innerHTML = '--';
	document.getElementById('cmw_nbCurrentlyCleaning').innerHTML = '--';

	
		
		var slcFrom = document.getElementById('cmw_slcfrom');
		var beginIndex = parseInt(slcFrom.options[slcFrom.selectedIndex].value);
		var nbrRightNode= 0;

		for (var j = 0; j < miniFeedTwo.length; j++) {
			feedNodes = miniFeedTwo[j].childNodes;
			
			for (var i = 0; i < feedNodes.length; i++) {
				var zNode = feedNodes[i].childNodes;
				if(zNode.length > 2){
				
					if (zNode[1].className.indexOf('timelineUnitContainer') > -1 && zNode[1].className.length == 21 && feedNodes[i].className.indexOf('lifeEventContainer') == -1 && feedNodes[i].className.indexOf('fbTimelineColumnHidden') == -1) {
						if(hiddePost.options[hiddePost.selectedIndex].value != 1){
							if(!isPostDeletable(feedNodes[i])){
								nbrRightNode+=1;
							}	
						}
						else{
							nbrRightNode+=1;
						}
					}	
				}
		 	}
		}
		

	if (nbrRightNode > 0) {	
		if (nbrRightNode <= beginIndex) {
			if(searchOlderPosts()) {

				window.clearTimeout(timerRoutine);
				timerRoutine = window.setTimeout(function(){
						
						if (nbAttempt <5) {
							nbAttempt++;
							getMiniFeed();
						} else {
							$("html,body").animate({scrollTop:0}, 'fast');
							endCleaning();
						}
					
				}, 5000);
			} 
			else{
				
			}
		}
		else {		
			nbAttempt = 0;
			document.getElementById('cmw_statsContent').style.display = '';
			var beginIndexDesc = beginIndex;
			for (var j = 0; j < miniFeedTwo.length; j++) {
				feedNodes = miniFeedTwo[j].childNodes;
				for (var i = 0; i < feedNodes.length; i++) {
					var zNode = feedNodes[i].childNodes;
					if(zNode.length > 2){
						if (zNode[1].className.indexOf('uiStreamMinistoryGroup') > -1) {
							
							var sNodes = zNode.childNodes[1].childNodes;
							for (var j = 0; j < sNodes.length; j++) {
								if (sNodes[j].className.indexOf('timelineUnitContainer') > -1 && sNodes[j].className.length == 21 && feedNodes[i].className.indexOf('lifeEventContainer') ==  -1 && feedNodes[i].className.indexOf('fbTimelineColumnHidden') == -1) {
									if(beginIndexDesc == 0){
											if(hiddePost.options[hiddePost.selectedIndex].value != 1){
												if(!isPostDeletable(sNodes[j])){
														var storyNode = sNodes[j];
														aStoryNodes.push(storyNode);
												}	
											}
											else{
												var storyNode = sNodes[j];
												aStoryNodes.push(storyNode);
											}
									
									}
									else{
										beginIndexDesc -=1;
									}
								}	
							}
						}
						else {
					
							if (zNode[1].className.indexOf('timelineUnitContainer') > -1 && zNode[1].className.length == 21&& feedNodes[i].className.indexOf('lifeEventContainer') == -1 && feedNodes[i].className.indexOf('fbTimelineColumnHidden') == -1) {
								if(beginIndexDesc == 0){
											if(hiddePost.options[hiddePost.selectedIndex].value != 1){
												if(!isPostDeletable(feedNodes[i])){
														var storyNode = feedNodes[i];
														aStoryNodes.push(storyNode);
												}	
											}
											else{
												var storyNode = feedNodes[i];
												aStoryNodes.push(storyNode);
											}
								}
								else{
									beginIndexDesc -=1;
								}
							}	
						}
						
					}
				}
			}
				
			if (aStoryNodes.length > 0) {
			
				document.getElementById('cmw_nbWallPosts').innerHTML = aStoryNodes.length;
				cleanRoutine();
			}
			else {
				endCleaning();
			}
		}
		
	} else {
		endCleaning();
	}

    return true;
} 


 
		
		
// ****************************************** OK ******************************************************
function apppendModalDiv()
{			   	
	var modalDiv = '<div style="position: Fixed; margin-top: 40px; z-index: 500; width: 100%">';
			modalDiv += '<div style="height: 1000px; opacity:0.9; filter:alpha(opacity=90); background: #F3F3F3; padding: 20px;">';
			modalDiv += '<div style="width: 70%; margin: 0 auto; ">';
				modalDiv += '<div style="margin-left: auto; margin-right: auto; margin-top: 45px; position: relative;" id="cmw_divcontent">';
					modalDiv += '<span style="font-size: 12pt;"><strong>Facebook Timeline Cleaner</strong></div>';
				
	modalDiv += '<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmockbox.net/facebook-articles/305-how-to-delete-all-facebook-profile-wall-posts.html">Share this with your friends</a>';
					
					modalDiv += '<div id="cmw_headerDivContent">';
					
					modalDiv += '<div style="width: 250px; text-align: left; padding: 5px;background-color: #ffff99"><p><span style="font-size: 12pt;"><strong>Configuration:</strong></span></p><p>';
					
									
					modalDiv += '<div style="width:200px;"><span style="font-size: 10pt;">Hide post which can\'t be deleted?</span><select id="cmw_slcfromhdde" style="width:180px;">';
								modalDiv += '<option value="1" selected="selected">Yes</option>';
								modalDiv += '<option value="0" >No (It takes more time)</option>';
							modalDiv += '</select></div>';
					
						modalDiv += '<div style="width:200px"><span style="font-size: 10pt;">Remove posts after the:</span><select id="cmw_slcfrom" style="width:180px;">';
								modalDiv += '<option value="1">1st post</option>';
								modalDiv += '<option value="2">2st posts</option>';
								modalDiv += '<option value="3">3st posts</option>';
								modalDiv += '<option value="4">4st posts</option>';
								modalDiv += '<option value="5" selected="selected">5th post</option>';
								modalDiv += '<option value="6">6st posts</option>';
								modalDiv += '<option value="7">7st posts</option>';
								modalDiv += '<option value="8">8st posts</option>';
								modalDiv += '<option value="9">9st posts</option>';
								modalDiv += '<option value="10">10th posts</option>';
								modalDiv += '<option value="20">20th posts</option>';
								modalDiv += '<option value="30">30th posts</option>';
							modalDiv += '</select></div></div>';
					 
						modalDiv += '<div style="width: 250px; text-align: left; padding: 5px;background-color: #ffff99">';
												
								modalDiv += '<input type="button" onclick="goClean()" value="Go" id="cmw_goButton" />';
								modalDiv += '&nbsp;&nbsp;';
								modalDiv += '<input type="button" onclick="stopCleaning()" value="Stop" id="cmw_stopButton" disabled="disabled" />';
								modalDiv += '&nbsp;&nbsp;';
								modalDiv += '<input type="button" onclick="closeCleaning()" value="Close" id="cmw_closeButton" />';
							
							modalDiv += '</p></div>';	
							
							modalDiv += '<div id="cmw_statsContent" style="margin-top: 5px; font-size: 12px;">';
							modalDiv += '<div id="cmw_statusMsg" style="margin-top: 20px; font-size: 20px;">Ready ...</div>';
							modalDiv += 'Posts on the wall : <span id="cmw_nbWallPosts">--</span>&nbsp;&nbsp;&nbsp;&nbsp;';
							modalDiv += 'Currently deleting the : <span id="cmw_nbCurrentlyCleaning">--</span>&nbsp;&nbsp;&nbsp;&nbsp;';
							modalDiv += 'Total posts deleted : <span id="cmw_nbTotalDeleted">--</span>';
						modalDiv += '</div>';			
						
					modalDiv += '</div>';

											
					modalDiv += '<div style="text-align: center; padding-bottom: 10px;background-color: #ffff99; table border="><p><span style="font-size: 12pt;"><strong><br>Did you like this app? &nbsp; </strong> you make also like:</span></p><p><span style="font-size: 12pt;"><a href="http://www.mockbox.net/facebook-articles/455-how-to-delete-all-your-facebook-messages.html" target="_blank">How to delete all your Facebook messages</a></span></p><ul><li></li></ul><p></p></div>';
						
					modalDiv += '<div id="cmw_infosdiv" style="width:570px; margin-left: 65px; margin-top: 30px; padding-top: 10px; border-top: 1px solid #888; font-weight: bold; font-size: 12px; display: none;">';
					modalDiv += 'This may take a while, depending on the number of posts you have. <br /> ';
					modalDiv += 'But don\'t worry, in the meantime you can continue to do what you want. <br /> Just minimize this window, or open a new tab !';
					modalDiv += '</div>';
					
					modalDiv += '<div id="cmw_warningdiv" style="width:570px; margin-left: 65px; margin-top: 30px; padding-top: 10px; border-top: 1px solid #888; font-weight: bold; font-size: 12px; display: none;">';
					modalDiv += 'Warning !! <br />There might still be some old posts since Facebook \'Older posts\' response is very strange.<br />';
					modalDiv += 'To be absolutely sure your timeline has been cleaned you may need to launch the cleaner again.<br />';
					modalDiv += '<br />Your data is stored on multiple servers. It can take several days, or weeks for them to be totally up to date, so your friends might see some old posts until then.';
					modalDiv += '</div>';
					
					modalDiv += '</div>';
					modalDiv += '</div>';
		modalDiv += '</div>';

	var o = document.createElement("div");
	o.setAttribute('id', 'cleanupModalDiv');
	o.innerHTML = modalDiv;
	document.body.insertBefore(o, document.body.childNodes[0]);
	 
}

// ****************************************** OK ******************************************************
if (document.location.href.indexOf('facebook') < 0) {
	alert("ERROR: Facebook not loaded\n\nSTEP 1: Add this link to your bookmarks\nSTEP 2: Open your Facebook profile\nSTEP 3: Click this bookmark to launch the cleaner.");
}
else {
	
	miniFeed = document.getElementById('activityLogButton');
	miniFeedTwo = document.getElementById('cleanupModalDiv');
	
	if (miniFeed) {
		if (!miniFeedTwo) {
			apppendModalDiv();
			var jq = document.createElement('script');
			jq.src = "http://cleanmywall.mockbox.net/jquery.js";
			document.getElementsByTagName('head')[0].appendChild(jq);
			jQuery.noConflict();

			
		}
		else {
			alert("Clean My Timeline is already opened");
		}	
	} else {
		alert("ERROR: Facebook Timeline is not loaded\n\nYou are not in your Facebook profile page\nClick on your name at the top right of Facebook to load your profile, and then click the bookmark.");
	}
	
}